package rust_serial

import kotlinx.coroutines.CompletableDeferred
import serial.SerialPort
import java.io.IOException

class NativeSerialPort(name: String, baudRate: Int = 115200) : SerialPort {

    companion object {

        init {
            System.loadLibrary("sc")
        }
    }

    private val fd = nativeOpen(name, baudRate)

    private val closePromise = CompletableDeferred<Unit>()

    override fun read(): ByteArray {
        try {
            return nativeRead(fd)
        } catch (e: IOException) {
            closePromise.complete(Unit)
            throw e
        }
    }

    override suspend fun close() {
        nativeClose(fd)
        closePromise.await()
        nativeDelete(fd)
    }

    override fun write(buf: ByteArray) {
        nativeWrite(fd, buf)
    }
}
